#!/usr/bin/python
"""Generate a wanlist template from a user's maths trade items.

It runs as a CGI service and provides a very basic template for either
by-hand wantlist creation, or to input into the spreadsheet.
"""

import cgi
import csv
import re
import sys
import StringIO

form = cgi.FieldStorage()
datafile = "/usr/local/rattus.net/data/cancon-trade-jan-2015.txt"

def GetItemsForUser(bgguser):
  bgguser = bgguser.strip()
  if not bgguser:
    return "", [], []

  data_username = ""
  codes = []
  names = []
  bgguser = bgguser.lower()

  try:
    fh = open(datafile, "r")
    csvfh = csv.reader(fh)
    headerline = csvfh.next()
    for row in csvfh:
      rowd = dict(zip(headerline, row))

      username = rowd["username"]
      mtcode = rowd["mtcode"]
      if username.lower() == bgguser:
        data_username = username
        codes.append(rowd["mtcode"])
        names.append(rowd["objectname"])

    return data_username, codes, names

  except IOError:
    return "", [], []


if __name__ == "__main__":
  argv = sys.argv[1:]
  if len(argv) == 2:
    datafile = argv[0]
    bgguser = argv[1]
  else:
    bgguser = form.getfirst("bgguser", "")

  print "Content-type: text/html"
  print

  print """<html>

  <head><title>BGG Maths trade wantlist template</title>
  <meta charset="UTF-8">
  <style type"text/css">
  .template {
    font-family: monospace;
  }
  </style>
  </head><body>


  <h1>Aussie Maths trade template generator</h1>

  <P>The purpose of this tool is to give people a template of all their
  own items for generating want-lists.

  <form method=get action="trade_template.py">
  BGG Username: <input type="text" name=bgguser>
  <input type=submit value="generate">
  </form>
  """

  (user,items, names) = GetItemsForUser(bgguser)
  if user and items:
    # Add these sections in only if we've got a valid template to show.
    hand_template = []
    spreadsheet_template1 = []
    spreadsheet_template2 = []
    for (item,name) in zip(items, names):
      hand_template.append("(%s) %s:" % (user, item))
      # spreadsheet_template.append("%s \t %s" % (name, item))
      spreadsheet_template1.append(name)
      spreadsheet_template2.append(item)

    print """
    <h2> Hand-filled template </h2>
    <P> Cut and paste this data into your text editor as a template for creating
    your own wantlists, if you are creating your want-list by hand.
    <div name="regular_template" class="template">
    <pre>%s
    </pre>
    </div>

    <h2> Spreadsheet Template</h2>
    If you are using the spreadsheet template
    <a href="https://docs.google.com/spreadsheet/ccc?key=0AolrpVU06cPidERBUUhHdUtUdmJsejZ5STRsc29IVXc">[link]</a>.
    <ol> <li> create a copy of the spreadsheet and rename it
    <li> replace bgguser with your own username.
    <li> select all names and paste them into the first column
    <li> select all codes and paste into the second column.
    <li> fill out the sizing, money value for each item
    <li> fill out your wanted items in the want-list tab
    </ol>
    <h3> Names </h3>
    <div name="spreadsheet_template1" class="template">
    <pre>%s</pre>
    </div>
    <h3> Codes </h3>
    <div name="spreadsheet_template2" class="template">
    <pre>%s</pre>
    </div>
    """  % ("\n".join(hand_template),
            "\n".join(spreadsheet_template1),
            "\n".join(spreadsheet_template2))
  # finis.
  print """</body>"""
